<template>
  <div>
    <div class="container">
      <div class="left">
        <i class="el-icon-user"></i>
        <i class="el-icon-chat-line-round"></i>
        <i class="el-icon-setting"></i>
      </div>
      <div class="right">
        <el-input
          placeholder="搜索用户"
          v-model="inputValue"
          class="custom-input"
          @input="handleSearch" 
          clearable 
        >
          <el-button 
            slot="append" 
            icon="el-icon-search"
            @click="loadUsers" 
          ></el-button>
        </el-input>
        <div class="list">
          <div
            class="content"
            v-for="(item, index) in listItems"
            :key="index"
            @click="selectItem(item)"
          >
            <div class="a">
              <img :src="require('../assets/logo.png')" alt="">
              <div class="text-container">
                <p class="title">{{ item.name }}</p>
                <p class="message">有消息</p>
              </div>
            </div>
            <p class="date">2025-03-23</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ChatAside',
  data() {
    return {
      inputValue: '',
      socket: null,
      listItems: [], // 存储用户列表
      searchTimer: null,
    };
  },
  watch: {
    // 监听搜索词变化（备选方案）
    inputValue(newVal) {
      if (newVal === '') this.loadUsers();
    }
  },
  created() {
    this.loadUsers();
  },
  methods: {
    handleSearch() {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.loadUsers();
      }, 300); // 300毫秒延迟
    },
    async loadUsers() {
      try {
        const response = await this.$axios.get('/user/page', {
          params: {
            pageNumber: 1,
            pageSize: 10,
            userName: this.inputValue.trim() // 使用去除前后空格的搜索关键词
          },
          headers: {
            Authorization: 'Bearer ' + localStorage.getItem('token')
          }
        });

        if (response.data.code === 0) {
          this.listItems = response.data.data.records.map(user => ({
            ...user,
            // 添加默认值防止undefined
            name: user.name || '未知用户',
            text: user.signature || '暂无签名',
            date: this.formatDate(user.lastOnline)
          }));
        } else {
          this.$message.error(response.data.msg || '搜索失败');
        }
      } catch (error) {
        console.error('搜索请求错误:', error);
        this.$message.error('搜索服务不可用');
        if (error.response?.status === 401) {
          this.$router.push('/login');
        }
      }
    },

    // 新增时间格式化方法
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getMonth() + 1}-${date.getDate()} ${
        date.getHours().toString().padStart(2, '0')}:${
        date.getMinutes().toString().padStart(2, '0')}`;
    },
  
    selectItem(item) {  // 修改为传递完整用户对象
      this.$bus.$emit('item-selected', item);
      this.$bus.$emit('set-current-target', item.id); // 设置当前聊天目标
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  width: 100%; 
}

.left {
  width: 80px;
  height: 100vh;
  background-color: black;
  display: flex;
  flex-direction: column;
  padding-top: 10px; 
  position: fixed;
  top: 0;
  left: 0;
}

.left i {
  margin: 5px;
}

.right {
  flex-grow: 1;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;
  margin-left: 80px; 
  /* background-color: #ccc; */

   /* 滚动条整体样式 */
   &::-webkit-scrollbar {
    width: 10px; /* 滚动条的宽度 */
  }

  /* 滚动条轨道 */
  &::-webkit-scrollbar-track {
    background: #f1f1f1; /* 轨道颜色 */
  }

  /* 滚动条滑块 */
  &::-webkit-scrollbar-thumb {
    background-color: gray; /* 滑块颜色 */
    border-radius: 5px; /* 圆角处理 */
  }

  /* 当前滚动条滑块状态 - 悬停时 */
  &::-webkit-scrollbar-thumb:hover {
    background-color: darkgray; /* 鼠标悬停时滑块颜色 */
  }
}


.custom-input>>> .el-input__inner {
  border: none;
}


.custom-input>>> .el-input__inner:focus {
  outline: none;
  box-shadow: none;
}
.list {
  width: 100%;
  height: 100vh;
  /* margin-left: 80px; */
}
.content {
  width: 100%;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #ccc;
}
.a {
  display: flex;
  align-items: flex-start; /* 垂直对齐方式为顶部对齐 */
  width: 100%;
  height: auto; 
}

.a img {
  width: 40px;
  height: 40px;
  margin-right: 5px; 
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2), 
  0 6px 20px rgba(0, 0, 0, 0.19);
}

.text-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 70%; 
}

.title {
  font-size: 16px; 
  margin: 0;
}

.message {
  font-size: 12px;
  margin: 0; 
  /* background-color: #f1f1f1; */
}

.date {
  margin-left: auto; /* 将日期推到容器的最右边 */
  align-self: flex-start; /* 对齐到下方（基于flex布局）*/
  font-size: 12px;
  background-color: white;
  width: 100px;
}
</style>